package com.wontube.client.io.protocol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Type;

import com.wontube.client.io.IObjectProtocol;
import com.wontube.client.utils.Base64;


/**
 * @author yuechao
 * 
 */
public final class JavaObjectProtocol implements IObjectProtocol {
	/*
	 * @see client.io.IObjectProtocol#toProtoString(java.lang.Object)
	 */
	@Override
	public String toProtoString(Object value) {
		if (value == null) {
			return "";
		}
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(bos);
			oos.writeObject(value);
			byte[] buffer = bos.toByteArray();
			String result = Base64.encode(buffer);

			return result;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				bos.close();
				if (oos != null) {
					oos.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/*
	 * @see client.io.IObjectProtocol#toObject(java.lang.String,
	 * java.lang.reflect.Type)
	 */
	@Override
	public Object toObject(String value, Type type) {
		if (value == null || "".equals(value)) {
			return null;
		}

		byte[] buffer = Base64.decode(value);
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(buffer));
			Object result = ois.readObject();
			return result;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				ois.close();
			} catch (IOException e) {
			}
		}
	}
}
